package com.niguang.work.labour.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.niguang.work.labour.api.entity.*;
import com.niguang.work.labour.api.enums.ManageTypeEnum;
import com.niguang.work.labour.api.mapper.TeamUserMapper;
import com.niguang.work.labour.api.service.*;
import com.niguang.work.labour.api.vo.TeamListVo;
import com.niguang.work.labour.common.constant.ResultCode;
import com.niguang.work.labour.common.pojo.Result;
import com.niguang.work.labour.common.util.ApiTokenUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 'work.v_personSite' is not BASE TABLE 服务实现类
 * </p>
 *
 * @author 83673
 * @since 2018-11-17
 */
@Service
public class TeamUserServiceImpl extends ServiceImpl<TeamUserMapper, TeamUser> implements TeamUserService {
    @Autowired
    private AdminLaborUserService adminLaborUserService;
    @Autowired
    private ApiTokenUtils apiTokenUtils;
    @Autowired
    private QiyeSiteService workQiyeSiteService;
    @Autowired
    private TypeService workTypeService;
    @Autowired
    private LaborCompanyService laborCompanyService;
    @Autowired
    private SiteUserService workSiteUserService;
    @Autowired
    private AppUserService workAppUserService;
    @Autowired
    private ReformUserService workReformUserService;
    @Autowired
    private WechatUserService wechatUserService;

    @Override
    public Result getTeamListUser(Page<Map<String, Object>> page, String teamId) {
        List<Map<String, Object>> teamListUser = baseMapper.getTeamListUser(page, teamId);
        Map<String, Object> map = new HashMap<>(4);
        page.setRecords(teamListUser);
        map.put("total", page.getTotal());
        map.put("list", page.getRecords());
        map.put("pages", page.getPages());
        map.put("current", page.getCurrent());
        return Result.build(ResultCode.SUCCESS, "班组列表成功！", map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addTeamUser(TeamUser workTeamUser) {
        final Long siteId = workTeamUser.getSiteId();
        Long userId = apiTokenUtils.getUserId();
        Long teamUserId = workTeamUser.getTeamUserId();
        AdminLaborUser adminLaborUser = adminLaborUserService.getById(userId);
        workTeamUser.setLaborCorompanyId(adminLaborUser.getLaborCompanyId());
        workTeamUser.setUserId(userId);
        QiyeSite workQiyeSite = workQiyeSiteService.getById(siteId);
        if (ObjectUtils.isEmpty(workQiyeSite) || workQiyeSite.getStatus() == 2) {
            return Result.build(ResultCode.PARAM_ERROR, "项目不存在或已结束");
        }
        QueryWrapper<Type> typeEntityWrapper = new QueryWrapper<>();
        typeEntityWrapper.eq(Type.NAME, "班组管理人").last("limit 1");
        Type workType = workTypeService.getOne(typeEntityWrapper);
        if (ObjectUtils.isEmpty(workType)) {
            return Result.build(ResultCode.PARAM_ERROR, "[班组管理人]类型未配置~");
        }
        workTeamUser.setWorkTypeId(workType.getId());
        // 检测当前添加人是否是 班组长
        QueryWrapper<TeamUser> entityWrapper = new QueryWrapper<>();
        entityWrapper.eq(TeamUser.TEAM_USER_ID, teamUserId).eq(TeamUser.SITE_ID, siteId).eq(TeamUser.DEL_FLAG, 0);
        List<TeamUser> workTeamUserList = baseMapper.selectList(entityWrapper);
        if (CollectionUtils.isNotEmpty(workTeamUserList)) {
            TeamUser workTeamUser1 = workTeamUserList.get(0);
            return Result.build(ResultCode.SUCCESS, "员工已是此工地[" + workTeamUser1.getBzName() + "]员工，不可再添加为班组长~");
        }

        try {
            Integer insert = baseMapper.insert(workTeamUser);
            if (insert > 0) {
                // ---------------------------- 存入工地员工表 start----------------------------------
                LaborCompany workLaborCompany = laborCompanyService.getById(adminLaborUser.getLaborCompanyId());
                SiteUser workSiteUser = new SiteUser(teamUserId, workQiyeSite.getQiyeId(), siteId, ManageTypeEnum.BZ_DESC.getIndex(), workType.getId(),
                        workLaborCompany.getLaborName(), adminLaborUser.getLaborCompanyId(), workTeamUser.getId(), workTeamUser.getMonthSalary(),
                        workTeamUser.getStartSalaryDate());

                boolean insert1 = workSiteUserService.save(workSiteUser);
                AppUser workAppUser = workAppUserService.getById(workTeamUser.getTeamUserId());
                if (!ObjectUtils.isEmpty(workAppUser)) {
                    QueryWrapper<ReformUser> entityWrapper2 = new QueryWrapper<>();
                    entityWrapper2.eq(ReformUser.SITE_ID, siteId).eq(ReformUser.USER_PHONE, workAppUser.getUserPhone())
                            .eq(ReformUser.DEL_FLAG, 0);
                    int count = workReformUserService.count(entityWrapper2);
                    if (count == 0) {
                        QueryWrapper<WechatUser> entityWrapper1 = new QueryWrapper<>();
                        entityWrapper1.eq(WechatUser.USER_PHONE, workAppUser.getUserPhone());
                        WechatUser workWechatUser = wechatUserService.getOne(entityWrapper1);
                        if (ObjectUtils.isEmpty(workWechatUser)) {
                            workWechatUser = new WechatUser();
                        }

                        ReformUser workReformUser = new ReformUser(workTeamUser.getSiteId(),
                                workTeamUser.getTeamUserId(), workAppUser.getUserName(), workAppUser.getUserPhone(),
                                workTeamUser.getBzName(), 1, "整改人", workWechatUser.getUnionId(), workWechatUser.getOpenId());
                        workReformUserService.save(workReformUser);
                    }
                }


                // ---------------------------- 存入工地员工表 end--------------------------------------
                return Result.build(ResultCode.SUCCESS, "班组长添加成功~");
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return Result.failed();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result delTeamUser(Long teamId) {
        TeamUser workTeamUser = baseMapper.selectById(teamId);
        if (ObjectUtils.isEmpty(workTeamUser)) {
            return Result.build(ResultCode.PARAM_ERROR, "班组长id[" + teamId + "]不存在！");
        }

        QueryWrapper<SiteUser> entityWrapper = new QueryWrapper<>();
        entityWrapper.eq(SiteUser.TEAM_ID, teamId).eq(SiteUser.DEL_FLAG, 0)
                .notIn(SiteUser.MANAGE_TYPE, 2);
        int count = workSiteUserService.count(entityWrapper);
        if (count > 0) {
            return Result.build(ResultCode.PARAM_ERROR, "班组长名下已设置员工，不可删除！");
        }
        Integer update = 0;
        try {
            update = baseMapper.updateById(new TeamUser(teamId, 1));
            QueryWrapper<SiteUser> entityWrapper1 = new QueryWrapper<>();
            entityWrapper1.eq(SiteUser.TEAM_ID, teamId);
            workSiteUserService.remove(entityWrapper1);
        } catch (Exception e) {

            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return Result.build(update > 0 ? ResultCode.SUCCESS : ResultCode.FAILED,
                update > 0 ? "删除班组成功!" : "删除班组失败！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result modifTeamUser(TeamUser workTeamUser) {
        TeamUser workTeamUser1 = baseMapper.selectById(workTeamUser.getId());
        if (ObjectUtils.isEmpty(workTeamUser1)) {
            return Result.build(ResultCode.PARAM_ERROR, "修改ID[" + workTeamUser.getId() + "]不存在~");
        }

        // 判断选择员工是否在班组成员里
        boolean isTeamUser = false;
        List<SiteUser> siteUserList = workSiteUserService.getSiteUserByUserTeamId(workTeamUser.getTeamUserId(), workTeamUser.getId());
        if (CollectionUtils.isNotEmpty(siteUserList)) {
            isTeamUser = siteUserList.stream().filter(p -> p.getManageType().equals(ManageTypeEnum.YG_DESC.getIndex())).count() > 0;
        }
        try {

            QueryWrapper<SiteUser> entityWrapper4 = new QueryWrapper<>();
            entityWrapper4.eq(SiteUser.TEAM_ID, workTeamUser.getId()).eq(SiteUser.SITE_ID, workTeamUser.getSiteId())
                    .eq(SiteUser.USER_ID, workTeamUser.getTeamUserId()).eq(SiteUser.MANAGE_TYPE, ManageTypeEnum.BZ_DESC.getIndex());
            int count = workSiteUserService.count(entityWrapper4);
            if (count > 0) {
                // 此用户已在本班组是班组长
                QueryWrapper<SiteUser> entityWrapper3 = new QueryWrapper<>();
                entityWrapper3.eq(SiteUser.TEAM_ID, workTeamUser.getId()).eq(SiteUser.MANAGE_TYPE, ManageTypeEnum.BZ_DESC.getIndex());
                SiteUser siteUser1 = new SiteUser();
                siteUser1.setManageType(ManageTypeEnum.BZ_DESC.getIndex());
                siteUser1.setDelFlag(1);
                workSiteUserService.update(siteUser1, entityWrapper3);
                entityWrapper3.eq(SiteUser.USER_ID, workTeamUser1.getTeamUserId());
                siteUser1.setDelFlag(0);
                workSiteUserService.update(siteUser1, entityWrapper3);
                baseMapper.updateById(workTeamUser);
                return Result.build(ResultCode.SUCCESS, "修改班组长成功~");
            }

            if (!workTeamUser1.getTeamUserId().equals(workTeamUser.getTeamUserId())) {
                // 选择班组长不在班组
                QueryWrapper<SiteUser> entityWrapper3 = new QueryWrapper<>();
                entityWrapper3.eq(SiteUser.TEAM_ID, workTeamUser.getId())
                        .eq(SiteUser.USER_ID, workTeamUser1.getTeamUserId()).eq(SiteUser.MANAGE_TYPE, ManageTypeEnum.BZ_DESC.getIndex());
                SiteUser siteUser1 = new SiteUser();
                siteUser1.setManageType(ManageTypeEnum.BZ_DESC.getIndex());
                siteUser1.setDelFlag(1);
                workSiteUserService.update(siteUser1, entityWrapper3);
            }


            if (isTeamUser) {
                // 选择人员是本班组员工，提升为班组长
                QueryWrapper<SiteUser> entityWrapper2 = new QueryWrapper<>();
                entityWrapper2.eq(SiteUser.TEAM_ID, workTeamUser.getId())
                        .eq(SiteUser.USER_ID, workTeamUser.getTeamUserId());
                SiteUser siteUser = new SiteUser();
                siteUser.setManageType(ManageTypeEnum.BZ_DESC.getIndex());
                siteUser.setDelFlag(0);
                siteUser.setCreateUserId(null);
                workSiteUserService.update(siteUser, entityWrapper2);
            } else {
                if (!workTeamUser1.getTeamUserId().equals(workTeamUser.getTeamUserId())) {
                    // 插入新班组员工
                    SiteUser workSiteUser = new SiteUser(workTeamUser.getTeamUserId(), null, workTeamUser.getSiteId(),
                            ManageTypeEnum.BZ_DESC.getIndex(), workTeamUser1.getWorkTypeId(), null,
                            workTeamUser1.getLaborCorompanyId(), workTeamUser.getId(), workTeamUser.getMonthSalary(),
                            workTeamUser.getStartSalaryDate());
                    workSiteUserService.save(workSiteUser);
                }
            }
            if (!workTeamUser1.getTeamUserId().equals(workTeamUser.getTeamUserId())) {
                QueryWrapper<SiteUser> siteUserEntityWrapper = new QueryWrapper<>();
                siteUserEntityWrapper.eq(SiteUser.TEAM_ID, workTeamUser.getId()).isNotNull(SiteUser.CREATE_USER_ID);
                workSiteUserService.update(new SiteUser(workTeamUser.getTeamUserId()), siteUserEntityWrapper);
            }
            baseMapper.updateById(workTeamUser);

            return Result.build(ResultCode.SUCCESS, "修改班组长成功~");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return Result.failed();
    }

    @Override
    public Result getTeamList(Page<TeamListVo> page, Long siteId) {
        Long userId = apiTokenUtils.getUserId();
        List<TeamListVo> teamList = baseMapper.getTeamList(page, siteId, userId);
        Map<String, Object> map = new HashMap<>(4);
        page.setRecords(teamList);
        map.put("total", page.getTotal());
        map.put("list", page.getRecords());
        map.put("pages", page.getPages());
        map.put("current", page.getCurrent());
        return Result.build(ResultCode.SUCCESS, "班组列表查询成功！", map);
    }
}
